const http = require('http')
const express = require('express')
const { Nuxt, Builder } = require('nuxt')

const nuxtConfig = require('../nuxt.config.js')
nuxtConfig.dev = !(process.env.NODE_ENV === 'production')

const port = 3000
const host = nuxtConfig.dev ? 'localhost' : '0.0.0.0'

const app = express()
const nuxt = new Nuxt(nuxtConfig)
const server = new http.Server(app)

app.use(nuxt.render)
app.set('port', port)

const bootstrap = () => {
  server.listen(port, host)
  const appName = "app"
  const envText = nuxtConfig.dev ? '开发模式' : '生产模式'
  console.info(`${appName} ${envText}启动成功！listening on ${host}:${port}, at ${new Date().toLocaleString()}`)
}

if (nuxtConfig.dev) {
  new Builder(nuxt).build().then(bootstrap).catch((error) => {
    console.error('开发模式启动失败：', error)
    process.exit(1)
  })
} else {
  bootstrap()
}
